
import React, { Component } from "react";
import AddTodo from "./add.jsx";
import Items from "./items.jsx";
import Tabs from "./tabs.jsx";
import "../../asserts/styles/todoList/index.scss";

class Todo extends Component {
  constructor() {
    super();
    this.state = {
      todoList: [],
      status: "all"
    };
  }
  addTodoList = value => {
    console.log(value)
    let todo = {
      value,
      status: "todo"
    };
    this.setState({ todoList: [...this.state.todoList, todo] });
  };
  finishItem = index => {
    let newArr = this.state.todoList.map((item, i) => {
      if (index !== i) {
        return item;
      }
      else {
        return {
          ...item,
          status: "finished"
        };
      }
    });
    this.setState({ todoList: newArr });
  };
  deleteItem = index => {
    let newArr = this.state.todoList.filter((item, i) => {
      return index !== i;
    });
    this.setState({ todoList: newArr });
  };
  withdrawItem = index => {
    let newArr = this.state.todoList.map((item, i) => {
      if (index !== i) {
        return item;
      } else {
        return {
          ...item,
          status: "todo"
        };
      }
    });
    this.setState({ todoList: newArr });
  };
  //处理Show组件分类展示的标签
  changeFilter = filter => {
    console.log('changeFilter')
    this.setState({ status: filter });
  };
  clearFinished = () => {
    let newArr = this.state.todoList.filter(item => {
      return item.status !== "finished";
    });
    this.setState({ todoList: newArr });
  };
  render() {
    let { todoList, status } = this.state;
    // 过滤数据，分类展示不同标签的列表
    let showedTodes;
    if (status === 'all') {
      showedTodes = todoList
    }
    else {
      showedTodes = todoList.filter(item => {
        return item.status === status;
      });
    }
    // 统计完成的todo
    let finishedNum = todoList.filter((item) => {
      return item.status === 'finished'
    }).length

    return (
      <div className="app">
        <AddTodo onAdd={this.addTodoList} />
        {this.state.todoList.length === 0 ? null : (
          <div>
            <Items
              todos={showedTodes}
              finishItem={this.finishItem}
              deleteItem={this.deleteItem}
              withdraw={this.withdrawItem}
            />
            <Tabs
              data={todoList}
              changeFilter={this.changeFilter}
            />
            <div className="clear">
              <p>
                完成度：{finishedNum} / {todoList.length}
              </p>
              <button
                type="button"
                className="btn btn-info"
                onClick={() => this.clearFinished}
              >
                清除完成项
              </button>
            </div>  
          </div>
        )}
      </div>
    );
  }
}

export default Todo;
